package com.example.administrator.xmut.cj;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.administrator.xmut.MainActivity;
import com.example.administrator.xmut.http.CourseBean;
import com.example.administrator.xmut.http.utils;
import com.example.administrator.xmut.kcb.GetTimeTable;
import com.example.administrator.xmut.kcb.ShowTimeTable;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/4/8.
 */

public class Getcj  extends AppCompatActivity {

    public static String gotourl="http://my.xmut.edu.cn/loginSuccess.portal";
    public static String gotoOnfail= "http://my.xmut.edu.cn/loginFailure.portal";
    public static String posturl="http://my.xmut.edu.cn/userPasswordValidate.portal";
    public static String geturl="http://my.xmut.edu.cn/index.portal";
    public static String jwxturl;
    public static String name="1407012215";
    public static String password="TamoQin0701";
    public static String responseCookie;
    public static String responseCookie1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AsyncHttpClient client = new AsyncHttpClient();
        // 创建请求参数
        RequestParams params = new RequestParams();
        params.put("Login.Token1", name);
        params.put("Login.Token2", password);
        params.put("goto", gotourl);
        params.put("gotoOnfail", gotoOnfail);
        // 执行post方法,并保存cookies
        saveCookie(client);

        client.post(posturl, params, new AsyncHttpResponseHandler() {
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                utils.setCookies(getCookie());
                Log.e("Getcj","1"+ String.valueOf(responseBody));
                AsyncHttpClient client1 = new AsyncHttpClient();
                if (utils.getCookies() != null) {//每次请求都要带上cookie
                    BasicCookieStore xxzxcookies = new BasicCookieStore();
                    xxzxcookies.addCookies(utils.getCookies().toArray(
                            new Cookie[utils.getCookies().size()]));
                    client1.setCookieStore(xxzxcookies);
                    // 发送get请求对象
                    client1.get(geturl, new AsyncHttpResponseHandler() {

                        Element name = null;
                        String jwxturl = null;

                        @Override
                        // statusCode:状态返回码，headers:头部请求信息，responseBody返回结果


                        public void onSuccess(int statusCode, Header[] headers, final byte[] responseBody) {
                            Log.e("Getcj", String.valueOf(responseBody));
                            try {
                                String resultContent = new String(responseBody, "utf-8");
                                Document doc = Jsoup.parse(resultContent);
                                jwxturl = doc.select("[href~=(default2)]").toString();
                                Log.e("Getcj",jwxturl);
                                Pattern pattern = Pattern.compile("href=['\"]([^'\"]*)['\"]");
                                Matcher matcher = pattern.matcher(jwxturl);
                                String aa = null;
                                if (matcher.find())
                                    aa = matcher.group(1);
                                jwxturl = aa.replace("amp;", "");
                                SharedPreferences mySharedPreferences = getSharedPreferences("test",
                                        MainActivity.MODE_PRIVATE);
                                SharedPreferences.Editor editor = mySharedPreferences.edit();
                                name = doc.getElementById("welcomeMsg");
                                editor.putString("jwxturl", jwxturl);
                                editor.putString("username", name.html());
                                editor.commit();
                                final String username = name.html();
                                new Thread(LoginJWXT).start();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }

                    });
                }
            }
        });

    }



    public void get() throws Exception{
        Log.e("dddd","12");
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        HttpURLConnection connection1 = null;
        HttpURLConnection connection2 = null;
        try {
            // 新建一个URL对象，指定到请求的url.
            SharedPreferences sharedPreferences= getSharedPreferences("test",
                    MainActivity.MODE_PRIVATE);
            String jwxturl = sharedPreferences.getString("jwxturl", "");
            URL url2 = new URL(jwxturl);
            connection = (HttpURLConnection) url2.openConnection();
            responseCookie = connection.getHeaderField("Set-Cookie");
            connection1 = (HttpURLConnection) url2.openConnection();
            connection1.setRequestProperty("Cookie",responseCookie);
            connection1.setRequestProperty("Host","210.34.213.67");
            connection1.setRequestProperty("Referer","http://my.xmut.edu.cn/");
            connection1.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
            reader = new BufferedReader(new InputStreamReader(connection1
                    .getInputStream(),"gb2312"));

            Log.e("dddd", responseCookie);

            URL url11 =new URL("http://210.34.213.67/xscjcx_dq.aspx?xh=1407012215&xm=%C1%D6%C0%A4%BA%A3&gnmkdm=N121605");
            HttpURLConnection conn1 = (HttpURLConnection)url11.openConnection();
            conn1.setDoOutput(true);
            conn1.setRequestProperty("Referer", "http://210.34.213.67/xscjcx_dq.aspx?xh=1407012215&xm=%C1%D6%C0%A4%BA%A3&gnmkdm=N121605");
            conn1.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36");
            conn1.setRequestProperty("Cookie",responseCookie);
            conn1.setRequestProperty("Host","http://210.34.213.67");
            conn1.setRequestMethod("GET");
            conn1.setConnectTimeout(5*1000);
            OutputStream outStream1 = conn1.getOutputStream();
            reader = new BufferedReader(new InputStreamReader(conn1
                    .getInputStream(),"gb2312"));
            Log.e("dddd", "777");
            String line11 = null;
            String html11 = null;
            while ((line11 = reader.readLine()) != null) {
                html11+=line11;
            }
            Document doc21 = Jsoup.parse(html11);
            String __VIEWSTATE = doc21.getElementById("Form1").select("input[name=__VIEWSTATE]").val();
            Log.e("dddd", __VIEWSTATE);
            String encoding="gb2312";
            String view=__VIEWSTATE.replace("+", "%2b");
            String content = "__EVENTTARGET="+" "+"&__EVENTARGUMENT="+" "+"&__VIEWSTATE="+view+"&ddlxn="+"2015-2016"+"&ddlxq="+"1"+"&btnCx="+"查  询";
            byte[] data = content.getBytes(encoding);
            URL url =new URL("http://210.34.213.67/xscjcx_dq.aspx?xh=1407012215&xm=%C1%D6%C0%A4%BA%A3&gnmkdm=N121605");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("Referer", "http://210.34.213.67/xscjcx_dq.aspx?xh=1407012215&xm=%C1%D6%C0%A4%BA%A3&gnmkdm=N121605");
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36");
            conn.setRequestProperty("Cookie",responseCookie);
            conn.setRequestProperty("Host","210.34.213.87");
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5*1000);
            OutputStream outStream = conn.getOutputStream();
            outStream.write(data);
            reader = new BufferedReader(new InputStreamReader(conn
                    .getInputStream(),"gb2312"));
            String line1 = null;
            String html1 = null;
            while ((line1 = reader.readLine()) != null) {
                html1+=line1;
            }
            Log.e("dddd", "555");
            List<Map<String, String>> list = new ArrayList<Map<String,String>>();
            Document doc2 = Jsoup.parse(html1);
            Elements ele = doc2.select(".datelist").select("tr");
            for(int i=0; i<ele.size(); i++){
                Elements tds = ele.get(i).select("td");
                Map<String, String> map =new HashMap<String, String>();
                for(int j=0; j<tds.size(); j++){
                    String tdText = tds.get(j).text();
                    map.put("td"+j, tdText);
                }
                list.add(map);
            }
            Log.e("dddd","list.get(2)");

            outStream1.flush();
            outStream1.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection.disconnect();
        }


    }

    Runnable LoginJWXT = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };

    //保存cookies的方法
    protected  void saveCookie(AsyncHttpClient client) {
        PersistentCookieStore cookieStore = new PersistentCookieStore(this);
        client.setCookieStore(cookieStore);
    }

    protected List<Cookie> getCookie(){
        PersistentCookieStore cookieStore = new PersistentCookieStore(this);
        List<Cookie> cookies = cookieStore.getCookies();
        return cookies;
    }

    public void clearCookie(){
        PersistentCookieStore cookieStore = new PersistentCookieStore(this);
        cookieStore.clear();
    }
}